<template>
	<PageWrapper title="基础表格(usetable)+搜索条件查询示例" contentFullHeight fixedHeight>
		<BasicTable @register="registerTable">
			<template #beforeTable>
				<div class="btns p-3">
					<a-button v-auth="`ADMIN`" class="mr-5" type="primary" @click="addNew">新增</a-button>
					<a-button type="primary" @click="getFormValue">获取form的值</a-button>
				</div>
			</template>
			<template #headerTop>
				<p>支持自定义headerTop</p>
			</template>
			<!-- title方法一 自定义tableTitle插槽 -->
			<!-- <template #tableTitle>
				<table-header title="质量台账" titleHelpMessage="温馨提示">
					<template #headerTop>
						<a href="">fjwoijfowiefwei</a>
					</template>
				</table-header>
			</template> -->
			<template #bodyCell="{ column, record }">
				<template v-if="column.key == 'approverStatus'">
					{{ ['通知单', '整改单'][record.approverStatus] }}
				</template>
				<template v-if="column.key == 'status'">
					{{ ['待接收', '处理中', '待销项', '已销项'][record.status - 1] }}
				</template>
				<template v-if="record.imgs && column.key == 'imgList'">
					<TableImg :size="60" :simpleShow="true" :imgList="record.imgs.map(item => item.url)" />
				</template>
				<template v-if="column.key == 'createTime'">
					{{ formatToDate(record.createTime) }}
				</template>
				<template v-if="column.key == 'action'">
					<TableAction
						:divider="true"
						:actions="[
							// 目前icon支持antd、iconfont和iconify，通过增加前缀区分
							{ icon: 'iconfont:icon-xiangqing', title: '详情', onClick: detail.bind(null, record) },
							{ icon: 'antd:EditOutlined', title: '编辑', onClick: edit.bind(null, record) },
							{
								icon: 'antd:ProfileOutlined',
								title: '流转记录',
								onClick: flow.bind(null, record),
								disabled: !hasPermission('test'),
							},
							{
								icon: 'fluent:delete-20-regular',
								color: 'error',
								title: '删除',
								popConfirm: { title: '是否确认删除', confirm: onDelete.bind(null, record) },
								ifShow: record.reformDate,
							},
						]"
					/>
				</template>
			</template>
		</BasicTable>
		<AddEventModalOwner @register="registerAddModal" @success="handleSuccess"></AddEventModalOwner>
		<EditEventModal @register="registerEditModal" @success="handleSuccess"></EditEventModal>
		<DetailDrawer @register="registerDrawer"></DetailDrawer>
	</PageWrapper>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { getBigTypes, getSafeList, getSmallTypes } from '@/api/demo';
import { BasicTable, TableAction, PageWrapper, TableImg } from '#/components';
import { useTable, useModal, useDrawer } from '#/hooks';
import { getAuthCache } from '@/utils/auth';
import { USER_INFO_KEY } from '@/enums/cacheEnum';
import type { BasicColumn } from '#/types';
import { formatToDate } from '@/utils/dateUtil';
import dayjs from 'dayjs';
import AddEventModalOwner from './components/AddModal.vue';
import EditEventModal from './components/EditModal.vue';
import DetailDrawer from './components/DetailDrawer.vue';
import { usePermission } from '@/hooks/web/usePermission';

const userId = getAuthCache<Recordable>(USER_INFO_KEY).userId;

export default defineComponent({
	name: 'UseTableDemo',
	components: { BasicTable, TableAction, PageWrapper, AddEventModalOwner, TableImg, EditEventModal, DetailDrawer },
	setup() {
		/**
		 * 1. 如果 @param dataIndex 和 @param key 值一样，且都是字符串或数字，则可省略其中一个
		 */
		const columns: BasicColumn[] = [
			{
				title: '编号',
				key: 'number',
				width: 135,
			},
			{
				title: '大类',
				dataIndex: 'typeBig',
				width: '8%',
			},
			{
				title: '小类',
				dataIndex: 'typeSmall',
				width: '10%',
			},
			{
				title: '类型',
				dataIndex: 'approverStatus',
				width: '8%',
			},
			{
				title: '状态',
				dataIndex: 'status',
				width: '5%',
			},
			{
				title: '图片',
				dataIndex: 'imgList',
				helpMessage: ['这是简单模式的图片列表', '只会显示一张在表格中', '但点击可预览多张图片'],
				width: 120,
			},
			/**
			 * @import 如果设置filter且查询字段名和dataIndex不一样，必须设置key作为正确的查询字段
			 */
			{
				title: '创建人',
				dataIndex: 'creator',
				key: 'creatorId',
				filters: [{ text: '我创建的', value: userId }],
				width: '8%',
			},
			{
				title: '创建时间',
				dataIndex: 'createTime',
				width: 120,
				sorter: true,
			},
			{
				title: '整改期限',
				dataIndex: 'reformDate',
				width: 120,
				sorter: (a: Recordable, b: Recordable) =>
					new Date(a.reformDate).getTime() - new Date(b.reformDate).getTime(),
			},
			// {
			// 	title: '销项时间',
			// 	dataIndex: 'reformFinish',
			// 	width: 120,
			// },
		];

		const { hasPermission } = usePermission();

		const [registerAddModal, { openModal: openAddModal }] = useModal();
		const [registerEditModal, { openModal: openEditModal }] = useModal();

		const [registerDrawer, { openDrawer }] = useDrawer();

		// #tableTitle
		const [registerTable, { reload, getForm }] = useTable({
			// title方法二：传title&titleHelpMessage(可选)+headerTop插槽
			title: '安全管理台账',
			titleHelpMessage: 'useTable',
			columns,
			showIndexColumn: true,
			api: getSafeList,
			useSearchForm: true,
			resetWithTableSearchInfo: true,
			formConfig: {
				labelAlign: 'left',
				labelWidth: 50,
				schemas: [
					{
						field: 'typeBigId',
						label: '大类',
						component: 'ApiSelect',
						colProps: {
							span: 4,
						},
						itemProps: {
							labelAlign: 'right',
						},
						componentProps: ({ formModel, formActionType }) => {
							return {
								api: getBigTypes,
								resultField: 'data',
								labelField: 'name',
								valueField: 'id',
								onChange: async e => {
									const { updateSchema } = formActionType;
									if (!e) {
										delete formModel.typeSmallId;
										updateSchema({
											field: 'typeSmallId',
											componentProps: {
												options: [],
											},
										});
										return;
									}
									const typeSmall = await getSmallTypes(e);
									formModel.typeSmallId = null;

									updateSchema({
										field: 'typeSmallId',
										componentProps: {
											options: typeSmall,
										},
									});
								},
							};
						},
					},
					{
						field: 'typeSmallId',
						label: '小类',
						component: 'ApiSelect',
						labelWidth: 50,
						colProps: {
							span: 4,
						},
						componentProps: {
							labelField: 'name',
							valueField: 'id',
							options: [],
							placeholder: '大类小类api联动',
						},
					},
					{
						field: 'status',
						label: '状态',
						colProps: {
							span: 4,
						},
						component: 'Select',
						componentProps: {
							options: [
								{
									label: '待销项',
									value: 1,
								},
								{
									label: '已销项',
									value: 2,
								},
							],
						},
					},
					{
						field: 'createTime',
						label: '创建时间',
						labelWidth: 80,
						colProps: {
							span: 8,
						},
						component: 'RangePicker',
						componentProps: {
							valueFormat: 'YYYY-MM-DD',
						},
					},
					{
						field: 'reformTime',
						label: '整改期限',
						labelWidth: 80,
						colProps: {
							span: 8,
						},
						component: 'RangePicker',
						componentProps: {
							valueFormat: 'YYYY-MM-DD HH:mm',
						},
					},
					{
						field: 'number',
						label: '关键字',
						labelWidth: 80,
						colProps: {
							span: 7,
						},
						componentProps: {
							placeholder: '请输入编号',
						},
						component: 'Input',
					},
				],
				fieldMapToTime: [
					['createTime', ['startCreateTime', 'endCreateTime'], 'YYYY-MM-DD'],
					['reformTime', ['startReformTime', 'endReformTime']],
				],
				autoSubmitOnEnter: true,
			},
			loading: true,
			rowKey: 'userId',
			rowClassName: rowClassName,
			actionColumn: {
				title: '操作',
				dataIndex: 'action',
				key: 'action',
				width: 340,
			},
		});

		function rowClassName(record: Recordable) {
			let day = dayjs().diff(record.reformDate, 'day');
			if (day > 3 && !record.reformFinish) {
				return 'table-hightlight';
			}
			return '';
		}

		function addNew() {
			openAddModal(true, { isUpdate: false });
		}

		function edit(record: Recordable) {
			openEditModal(true, { record });
		}

		function onDelete(record: Recordable) {
			console.log(record);
			reload();
		}

		function flow(record: Recordable) {
			console.log(record);
		}

		function detail(record: Recordable) {
			openDrawer(true, { record });
		}

		function getFormValue() {
			console.log(getForm().getFieldsValue());
		}

		function handleSuccess() {
			reload();
		}
		return {
			hasPermission,
			addNew,
			edit,
			onDelete,
			flow,
			detail,
			registerTable,
			registerAddModal,
			registerEditModal,
			registerDrawer,
			handleSuccess,
			formatToDate,
			getFormValue,
		};
	},
});
</script>
<style lang="less" scoped>
:deep(.table-hightlight) .ant-table-cell {
	background: #ffefef !important;
}
</style>
